<script setup>
import { ref } from 'vue'
import useUserInfoStore from '@/stores/userInfo.js';
import { useTokenStore } from '@/stores/token.js';
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()

const userData = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})
const checkRePassword = (rule, value, callback) => {
    // 检查新密码是否已被填充
    if (userData.value.new_pwd === '') {
        callback(new Error('请先输入新密码'));
    } 
    // 检查两次输入密码是否一致
    else if (userData.value.re_pwd !== userData.value.new_pwd) {
        callback(new Error('请保证两次输入密码一致'));
    } else {
        callback();
    }
}
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5-16位非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5-16位非空字符', trigger: 'blur' }
    ],
    rePassword: [
        { validator: checkRePassword, trigger: 'blur' }
    ]
}
import { userPasswordUpdateService } from '@/api/user';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
const router = useRouter()
const updatePwdPassword = async ()=>{
    try {
        await userPasswordUpdateService(userData.value);
        ElMessage.success('修改成功');

        tokenStore.removeToken()
        userInfoStore.removeInfo()
        router.push('/login');
    } catch (error) {
    }
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>修改密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="10">
                <el-form :model="userData" :rules="rules" label-width="120px" size="large">
                    <el-form-item label="原密码">
                        <el-input v-model="userData.old_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码">
                        <el-input v-model="userData.new_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="再次输入新密码" prop="rePassword">
                        <el-input v-model="userData.re_pwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click = "updatePwdPassword">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>